import { Link, NavLink, Outlet, useLocation, useSearchParams } from "react-router-dom";
import { getInvoices} from "../data/data_invoices"

export default function Invoices() {
  let invoices = getInvoices();
  let [searchParams, setSearchParams] = useSearchParams();
  return (
    <div style={{ display: "flex" }}>
      <nav
        style={{
          borderRight: "solid 1px",
          padding: "1rem",
        }}
      >
        <input
          value={searchParams.get("filter") || ""}
          onChange={(e)=>{
            let filter = e.target.value;
            if(filter){
              setSearchParams({
                filter: filter
              });
            }else{
              setSearchParams({});
            }
          }}
        ></input>
        {invoices.filter((invoice)=>{
          let filter = searchParams.get("filter");
          if(!filter){
            return true
          }
          let name = invoice.name.toLowerCase();
          return name.startsWith(filter.toLowerCase());
        }).map((invoice) => (
          <QueryLink
            style={{ display: "block", margin: "1rem 0" }}
            to={`/invoices/${invoice.number}`}
            key={invoice.number}
          >
            {invoice.name}
          </QueryLink>
        ))}
      </nav>
      <Outlet></Outlet>
    </div>
  );
}

function QueryLink({
  to,
  ...props
}){
  let location = useLocation();
  return <NavLink
    to={to + location.search}
    {...props}
  ></NavLink>
}